package vn.gq.udv.utils;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.Log;


public class GQUtils {
	
	public static final long MIN_SDCARD_FREE_SPACE = 1024 * 1024 * 1024 * 50;			// 50MB
	public static final long MIN_PHONE_FREE_SPACE = 1024 * 1024 * 1024 * 20;			// 20MB
	public static final String DS = File.separator;

	public enum MemoryType {
		SDCARD, PHONE
	}
	
	public static String getPhoneIMEI(Context ctx) {
		TelephonyManager tMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
		return tMgr.getDeviceId();
	}
	
	public static int getVersionCode(Context ctx) {
		try {
			return ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public static String getPhoneInfo(Context ctx) {
		TelephonyManager tMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
		return tMgr.getDeviceId()+"|"+tMgr.getNetworkOperatorName()+"|"+tMgr.getLine1Number()+"|"+tMgr.getSimSerialNumber()+"|"+tMgr.getSubscriberId();
	}
	
	public static String md5(String input) {
		try {
			StringBuilder sb = new StringBuilder();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(input.getBytes());
			byte[] hashByte = md.digest();
			for (int i=0;i<hashByte.length;i++) {
				sb.append(Integer.toHexString((hashByte[i] & 0xff) | 0x100).substring(1, 3));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static long freeMem(MemoryType type) {
		long free = 0L;	
		StatFs stat = null;
		switch (type) {
			case SDCARD:
				stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
				stat.restat(Environment.getExternalStorageDirectory().getAbsolutePath());
				break;
			default:
				stat = new StatFs("/data");
				stat.restat("/data");
		}
		free = (long) ((long) stat.getAvailableBlocks() * (long) stat.getBlockSize());
		return free;
	}
	
	public static boolean sdCardIsReady() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && freeMem(MemoryType.SDCARD) > MIN_SDCARD_FREE_SPACE; 
	}
}
